﻿using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Domain.Model;
using Infrastructure;
using System.Configuration;
using Domain.Model.Enums;

namespace Web.Controllers
{
    /// <summary>
    /// 系统控制器
    /// </summary>
    public class MemberController : LoginedController
    {
        /// <summary>
        /// 主页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            ViewData["news"] = DbContext.News.OrderByDescending(i => i.CreateTime).Take(7).ToList();
            var model = DbContext.User.Find(LoginUser.ID);
            return View(model);
        }
        public ActionResult CheckOut()
        {
            Session["LoginUser"] = null;
            return Redirect("/Home/index");
        }

        #region 交易中心
        public ActionResult TradingMaket()
        {
            ViewData["Member"] = DbContext.User.Find(LoginUser.ID);

            var model = this.DbContext.GameBean.OrderBy(item => item.CreateTime).ToArray()
                        .Select(item => new Domain.Model.DTO.KeyValue<string, double>
                        {
                            Key = item.CreateTime.ToString("yy/MM/dd HH:mm:ss"),
                            Value = (double)item.Price
                        })
                        .ToList();
            return View(model);
        }
        #endregion

        #region 团队管理
        //注册
        public ActionResult Register()
        {
            var item = new List<SelectListItem>();
            item.Add(new SelectListItem() { Text = "男", Value = "1" });
            item.Add(new SelectListItem() { Text = "女", Value = "0" });
            ViewData["Gender"] = item;

            User model = new User()
            {
                //Account = DbContext.Database.NewCustormerNo(),
                RoleId = DbContext.Role.Where(i => i.Name == "会员").SingleOrDefault().ID
            };
            return View(model);
        }
        [HttpPost]
        public ActionResult Register(User model)
        {
            try
            {
                model.Password = Infrastructure.Encryption.GetPasswordMd5(model.Password);
                model.ExchangePassword = Infrastructure.Encryption.GetPasswordMd5(model.ExchangePassword);
                model.LastLoginTime = DateTime.Now;
                model.ReferrerId = LoginUser.ID;
                //等级
                switch (model.Level)
                {
                    case Levels.L1:
                        model.NvestmentAmount = 1000;
                        model.DeclarationToken = 1000;
                        model.BounsPush = model.NvestmentAmount * (decimal)0.8;
                        break;
                    case Levels.L2:
                        model.NvestmentAmount = 2000;
                        model.DeclarationToken = 2000;
                        break;
                    case Levels.L3:
                        model.NvestmentAmount = 3000;
                        model.DeclarationToken = 3000;
                        break;
                    case Levels.L4:
                        model.NvestmentAmount = 4000;
                        model.DeclarationToken = 4000;
                        break;
                    case Levels.L5:
                        model.NvestmentAmount = 5000;
                        model.DeclarationToken = 5000;
                        break;
                    default:
                        break;
                }
                model.GameBean = model.NvestmentAmount / 2;
                model.OutMultiple = 4;

                DbContext.User.Add(model);
                DbContext.SaveChanges();
                return Json(new { state = true, value = "/member/ActivateMember" });
            }
            catch (Exception ex)
            {
                return Json(new { state = false, value = ex.Message });
            }
        }

        //安置网络图注册
        public ActionResult PositionRegister(int position)
        {
            var model = new User();
            model.ContactPerson = LoginUser.Name;
            model.Position = (Position)position;
            return View("Register", model);
        }
        //团队系谱图
        public ActionResult TeamChar()
        {

            return View();
        }

        //推荐结构
        public ActionResult RecommendChar()
        {

            return View();
        }
        //激活会员
        public ActionResult ActivateMember()
        {
            var where = Where.True<User>();
            where = where.And(i => i.ReferrerId == LoginUser.ID);
            ViewBag.Count = DbContext.User.Where(where).Count();
            ViewBag.Total = DbContext.User.Sum(i => i.DeclarationToken);
            return View();
        }
        public ActionResult ActivateMemberPage(int pageIndex, int pageSize, string keyword)
        {
            var where = Where.True<User>();
            where = where.And(i => i.ReferrerId == LoginUser.ID);
            var page = DbContext.User
                .Where(where).OrderByDescending(i => i.CreateTime).ToPage(pageIndex, pageSize);
            return this.PageResult(page.TotalCount, this.ViewHtml(page));
        }
        #endregion

        #region 电子银行
        //入账明细
        public ActionResult ComeDetail()
        {

            return View();
        }
        public ActionResult ComeDetailPage(int pageIndex, int pageSize, string keyword)
        {
            var where = Where.True<FinanceDetail>();
            where = where.And(i => i.FinanceType == FinanceType.入账);
            if (keyword != null)
            {
                where = where.And(i => i.MemberNo.Contains(keyword));
            }
            var page = DbContext.FinanceDetail
                .Where(where).OrderByDescending(i => i.CreateTime).ToPage(pageIndex, pageSize);
            return this.PageResult(page.TotalCount, this.ViewHtml(page));
        }
        //出账明细
        public ActionResult OutDetail()
        {

            return View();
        }
        public ActionResult OutDetailPage(int pageIndex, int pageSize, string keyword)
        {
            var where = Where.True<FinanceDetail>();
            where = where.And(i => i.FinanceType == FinanceType.出账);
            if (keyword != null)
            {
                where = where.And(i => i.MemberNo.Contains(keyword));
            }
            var page = DbContext.FinanceDetail
                .Where(where).OrderByDescending(i => i.CreateTime).ToPage(pageIndex, pageSize);
            return this.PageResult(page.TotalCount, this.ViewHtml(page));
        }
        //奖金明细
        public ActionResult BonusDetail()
        {
            return View();
        }
        public ActionResult BonusDetailPage(int pageIndex, int pageSize, string keyword)
        {
            var where = Where.True<FinanceBonusReport>();

            if (keyword != null)
            {
                where = where.And(i => i.MemberNo.Contains(keyword));
            }
            var page = DbContext.FinanceBonusReport
                .Where(where).OrderByDescending(i => i.CreateTime).ToPage(pageIndex, pageSize);
            return this.PageResult(page.TotalCount, this.ViewHtml(page));
        }
        //会员转账
        public ActionResult MemberTransfer()
        {
            var transfer = new Transfer();
            return View(transfer);
        }
        [HttpPost]
        public ActionResult MemberTransfer(string type, string amount, string userIn)
        {
            try
            {
                var transferAmount = decimal.Parse(amount);
                var UserIn = DbContext.User.Where(i => i.Account == userIn).FirstOrDefault();
                if (UserIn == null)
                {
                    return Json(new { state = false, value = "接受会员账号不存在" });
                }
                var Member = DbContext.User.Find(LoginUser.ID);



                if (type == "电子币钱包")
                {
                    if (Member.ElectronicToken < transferAmount)
                    {
                        return Json(new { state = false, value = "电子币不足" });
                    }
                    Member.ElectronicToken = Member.ElectronicToken - transferAmount;
                    UserIn.ElectronicToken = UserIn.ElectronicToken + transferAmount;
                }
                else
                {
                    if (Member.DeclarationToken < transferAmount)
                    {
                        return Json(new { state = false, value = "报单币不足" });
                    }
                    Member.DeclarationToken = Member.DeclarationToken - transferAmount;
                    UserIn.DeclarationToken = UserIn.DeclarationToken + transferAmount;
                }

                Transfer model = new Transfer();

                model.UserId = LoginUser.ID;
                model.Amount = transferAmount;
                model.UserIn = userIn;
                model.TransferType = type;
                model.MenberOut = LoginUser.Account;

                DbContext.Transfer.Add(model);

                DbContext.User.Update(DbContext, Member);
                DbContext.SaveChanges();

                return Json(new { state = true, value = "转账成功" });
            }
            catch (Exception ex)
            {
                return Json(new { state = false, value = ex.Message });
            }
        }

        public ActionResult MemberTransferPage(int pageIndex, int pageSize, string keyword)
        {
            var where = Where.True<FinanceDetail>();
            where = where.And(i => i.FinanceType == FinanceType.出账);
            if (keyword != null)
            {
                where = where.And(i => i.MemberNo.Contains(keyword));
            }
            var page = DbContext.FinanceDetail
                .Where(where).OrderByDescending(i => i.CreateTime).ToPage(pageIndex, pageSize);
            return this.PageResult(page.TotalCount, this.ViewHtml(page));
        }
        //提现申请
        public ActionResult Withdraw()
        {
            ViewData["UserBank"] = DbContext.UserBank.Where(i => i.UserId == LoginUser.ID).FirstOrDefault();
            ViewBag.Total = DbContext.Withdraw.Where(i => i.MemberId == LoginUser.ID).Sum(i => i.NowAmount);
            var model = new Withdraw();
            return View();
        }
        //保存提现
        public ActionResult SaveWithdraw(Withdraw model, string password)
        {
            try
            {
                if (LoginUser.ExchangePassword != Encryption.GetPasswordMd5(password))
                {
                    return Json(new { state = false, value = "交易密码错误" });
                }
                var bank = DbContext.UserBank.Where(i => i.UserId == LoginUser.ID).FirstOrDefault();
                model.MemberId = LoginUser.ID;
                model.MemberNo = LoginUser.Account;
                model.BankName = bank.Bank.GetDisplay();
                model.BankNo = bank.Account;
                model.BankUser = bank.UserName;
                model.Address = bank.Address;
                model.state = State.未发放;
                model.WithdrawType = "奖金币钱包";
                model.Poundage = 0;
                DbContext.Withdraw.Add(model);
                DbContext.SaveChanges();
                return Json(new { state = true, value = "success" });
            }
            catch (Exception ex)
            {
                return Json(new { state = false, value = ex.Message });
            }
        }
        //提现记录
        public ActionResult WithdrawPage(int pageIndex, int pageSize, string keyword)
        {
            var where = Where.True<Withdraw>();
            where = where.And(i => i.MemberId == LoginUser.ID);
            if (keyword != null)
            {
                where = where.And(i => i.MemberNo.Contains(keyword));
            }
            var page = DbContext.Withdraw
                .Where(where).OrderByDescending(i => i.CreateTime).ToPage(pageIndex, pageSize);
            return this.PageResult(page.TotalCount, this.ViewHtml(page));
        }
        //货币转换
        public ActionResult CurrencyTransfer()
        {

            return View();
        }
        [HttpPost]
        public ActionResult CurrencyTransfer(string type, string amount, string password)
        {
            try
            {
                var transferAmount = decimal.Parse(amount);
                var Member = DbContext.User.Find(LoginUser.ID);
                if (Member.ExchangePassword != Encryption.GetPasswordMd5(password))
                {
                    return Json(new { state = false, value = "交易密码错误" });
                }
                if (type == "奖金币转报单币")
                {
                    if (Member.Bonus < transferAmount)
                    {
                        return Json(new { state = false, value = "奖金币不足" });
                    }
                    Member.Bonus -= transferAmount;
                    Member.DeclarationToken += transferAmount;
                }
                else
                {
                    if (Member.DeclarationToken < transferAmount)
                    {
                        return Json(new { state = false, value = "报单币不足" });
                    }
                    Member.DeclarationToken -= transferAmount;
                    Member.Bonus += transferAmount;
                }


                DbContext.User.Update(DbContext, Member);
                DbContext.SaveChanges();

                return Json(new { state = true, value = "转换成功" });
            }
            catch (Exception ex)
            {
                return Json(new { state = false, value = ex.Message });
            }
        }
        //在线充值电子币
        public ActionResult ElectronicToken()
        {
            var bank = DbContext.UserBank.Where(i => i.UserId == LoginUser.ID).FirstOrDefault();
            var pay = new Pay()
            {
                MemberNo = LoginUser.Account,
                UserID = LoginUser.ID,
                PayBankName = bank != null ? bank.Bank.GetDisplay() : ""
            };
            return View(pay);
        }
        public ActionResult ElectronicTokenPage(int pageIndex, int pageSize, string keyword)
        {
            var where = Where.True<Pay>();
            where = where.And(i => i.UserID == LoginUser.ID);
            if (keyword != null)
            {
                where = where.And(i => i.MemberNo.Contains(keyword));
            }
            var page = DbContext.Pay
                .Where(where).OrderByDescending(i => i.CreateTime).ToPage(pageIndex, pageSize);
            return this.PageResult(page.TotalCount, this.ViewHtml(page));
        }
        //保存充值电子币
        public ActionResult SaveElectronicToken(Pay model, string ExchangePassword)
        {
            try
            {
                if (LoginUser.ExchangePassword != Encryption.GetPasswordMd5(ExchangePassword))
                    return Json(new { state = false, value = "交易密码错误" });
                model.UserID = LoginUser.ID;
                model.State = State.审核中;
                DbContext.Pay.Add(model);
                DbContext.SaveChanges();
                return Json(new { state = true, value = "success" });
            }
            catch (Exception ex)
            {
                return Json(new { state = false, value = ex.Message });
            }
        }
        #endregion

        #region 安全信息
        //个人资料
        public ActionResult MemberInfo()
        {
            var model = LoginUser;
            return View(model);
        }
        //修改资料
        public ActionResult MemberEdit()
        {
            var model = LoginUser;
            return View(model);
        }
        [HttpPost]
        public ActionResult MemberEdit(string nickName, Genders Gender, string address, string telPhone)
        {
            try
            {
                var model = LoginUser;
                model.NickName = nickName;
                model.Gender = Gender;
                model.Address = address;
                model.TelPhone = telPhone;
                DbContext.User.Update(DbContext, model);
                DbContext.SaveChanges();
                return Json(new { state = true });
            }
            catch (Exception ex)
            {
                return Json(new { state = false, value = ex.Message });
            }
        }
        //银行资料
        public ActionResult BankInfo()
        {
            UserBank model;
            var hasBank = DbContext.UserBank.Any(i => i.UserId == LoginUser.ID);
            if (hasBank)
                model = DbContext.UserBank.Where(i => i.UserId == LoginUser.ID).FirstOrDefault();
            else
                model = new UserBank();
            return View(model);
        }
        [HttpPost]
        public ActionResult BankInfo(UserBank model)
        {
            model.UserId = LoginUser.ID;
            try
            {
                if (DbContext.UserBank.Any(i => i.UserId == model.UserId && i.Bank == model.Bank))
                {
                    var id = DbContext.UserBank.Where(i => i.UserId == model.UserId && i.Bank == model.Bank).Select(i => i.ID).FirstOrDefault();
                    model.ID = id;
                    DbContext.UserBank.Update(DbContext, model);
                }
                else
                {
                    DbContext.UserBank.Add(model);
                }
                DbContext.SaveChanges();
                return Json(new { state = true });
            }
            catch (Exception ex)
            {

                return Json(new { state = false, value = ex.Message });
            }
        }
        //切换银行
        [HttpPost]
        public ActionResult ChangeBank(UserBank userBank)
        {
            if (DbContext.UserBank.Any(i => i.UserId == LoginUser.ID && i.Bank == userBank.Bank))
            {
                var model = DbContext.UserBank.Where(i => i.UserId == LoginUser.ID && i.Bank == userBank.Bank).FirstOrDefault();
                return Json(new { state = true, Account = model.Account, Address = model.Address, UserName = model.UserName });
            }
            else
            {
                return Json(new { state = false });
            }
        }
        //修改密码
        public ActionResult MemberPassword()
        {
            return View();
        }
        public ActionResult ChangePassword(string title, int type)
        {
            ViewBag.title = title;
            ViewData["type"] = type;
            return View();
        }
        [HttpPost]
        public ActionResult ChangePassword(string oldPassword, string newPassword, int type)
        {
            if (LoginUser.Password == Encryption.GetPasswordMd5(oldPassword))
            {
                if (type == 0)
                    LoginUser.Password = Encryption.GetPasswordMd5(newPassword);
                else
                    LoginUser.ExchangePassword = Encryption.GetPasswordMd5(newPassword);
                DbContext.User.Update(DbContext, LoginUser);
                DbContext.SaveChanges();
                return Json(new { state = true });
            }
            else
            {
                return Json(new { state = false, value = "密码错误!" });
            }

        }
        #endregion

        #region 服务台
        //最新公告
        public ActionResult NewInfo()
        {
            var news = DbContext.News.OrderByDescending(i => i.CreateTime).ToList();
            return View(news);
        }
        public ActionResult NewDetail(Guid id)
        {
            var model = DbContext.News.Find(id);
            return View(model);
        }
        //留言
        public ActionResult Guestbook()
        {
            var model = new Guestbook();
            return View(model);
        }
        [HttpPost]
        public ActionResult Guestbook(Guestbook model)
        {
            try
            {
                model.GuestId = LoginUser.ID;
                DbContext.Guestbook.Add(model);
                DbContext.SaveChanges();
                return Json(new { state = true });
            }
            catch (Exception ex)
            {
                return Json(new { state = false, value = ex.Message });
            }
        }
        #endregion
    }
}
